<?php
namespace Orm\UserAccount;

class UserAccountModel extends \Base\BaseOrmModel{

    function __construct()
    {
        parent::__construct();
        $this->table = 't_user_account';
    }

    /**
     * @param $uid
     * @return array
     * @throws \Base\Exception\NoRecordException
     */
    public function getUserAccountByUid($uid)
    {
        $result = $this->fetchOne('*', "`uid`='{$uid}' AND `is_del` = 0");
        if ($result) {
            return $result;
        }
        throw new \Base\Exception\NoRecordException("No record find by id [{$uid}]");
    }

    /**
     * @param $filed
     * @param $limit
     * @return array
     * 获取周排行积分前150名
     */
    public function getUserAccountList($filed,$limit){
        $sql = "SELECT id,uid,nickname,".$filed." FROM ".$this->table." WHERE `is_del` = 0 AND {$filed} > 0 ORDER BY ".$filed." DESC LIMIT ".$limit;
        return $this->_fetch($sql,1);
    }

    /**
     * @param $offset
     * @param $size
     * @param $type
     * @param $order
     * @return mixed
     * 获取总排行-周排行
     */
    public function getUserAccountRank($offset,$size,$type,$order,$week_type=0){
        $filed = "a.uid,a.nickname,b.headimgurl";
        $where = 'a.is_del = 0 ';
        if($type == \Orm\UserAccount\UserAccountClass::SCORE_TYPE_TOTAL){//周排行
            $filed .= ",a.score";
            $where .=" AND a.score > 0";
        }elseif ($type == \Orm\UserAccount\UserAccountClass::SCORE_TYPE_WEEK){
            $filed .= ",a.one_week_score,a.two_week_score,a.three_week_score,a.four_week_score";
            if ($week_type == 1) {
                $where .=" AND a.one_week_score > 0";
            }
            if ($week_type == 2) {
                $where .=" AND a.two_week_score > 0";
            }
            if ($week_type == 3) {
                $where .=" AND a.three_week_score > 0";
            }
            if ($week_type == 4) {
                $where .=" AND a.four_week_score > 0";
            }
        }
        $sql = "SELECT ".$filed." FROM ".$this->table." a LEFT JOIN t_user b ON a.uid = b.id WHERE ".$where;
        if($order != ''){
            $sql .= " ORDER BY ".$order;
        }
        $re['total'] = $this->_fetch($sql, 2) ?$this->_fetch($sql, 2) : 0;
        $sql .= " LIMIT " . $offset . "," . $size;
        $re['list'] = $this->_fetch($sql, 1) ? $this->_fetch($sql, 1): array();
        return $re;
    }
}